package com.example.schoolassets;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.KeyEvent;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.seuic.scankey.IKeyEventCallback;
import com.seuic.scankey.ScanKeyService;
import com.seuic.scanner.DecodeInfo;
import com.seuic.scanner.DecodeInfoCallBack;
import com.seuic.scanner.Scanner;
import com.seuic.scanner.ScannerFactory;
import com.seuic.uhf.EPC;
import com.seuic.uhf.UHFService;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.BasicMessageChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.StandardMessageCodec;
import io.flutter.plugins.GeneratedPluginRegistrant;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends FlutterActivity implements DecodeInfoCallBack {
    private BasicMessageChannel messageChannel;
    //    public static RFIDWithUHFUART mUhfrManager;// uhf
    private boolean loopFlag = false;
    Handler RFIDhandler;
    public MainActivity mContext;
    // rfid模块初始化状态
    public boolean init;
    //    扫描类
//    public Barcode2DWithSoft barcode;
//    Barcode2DWithSoft barcode=null;
    String barCode = "";
    String seldata = "ASCII";
    Handler RFIDSetPowerhandler;
    Handler RFIDGetPowerhandler;
    Handler Scanhandler;
    Handler InitScanhandler;
    Handler ReadRFIDOnehandler;
    Handler ReadRFIDSearch2handler;
    //    广播
    private IntentFilter intentFilter;
    private MyBroadcastReceiver myBroadcastReceiver;

    //AUTOID UTouch(c)手持机操作
    UHFService UTouchUHF;
    //    private InventoryRunable mInventoryRunable;
    public static boolean mInventoryStart = false;
    private Thread mInventoryThread;
    private List<String> mEPCList = new ArrayList<String>();
    private MutableLiveData<List<EPC>> mEPCListLiveData;
    Scanner scanner;
    String ModelDevice = Build.MODEL;

    private ScanKeyService mScanKeyService;
    private IKeyEventCallback mCallback;
    //    摁键摁下次数
    int Num = 0;
    //    长嗯次数
    int LongNum = 0;
    //摁下次数递增线程开启或者关闭
    boolean IsNum = false;
    List<String> TIDlist = new ArrayList<String>();
    String Token = "";
    public MainActivity() {
    }

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        messageChannel = new BasicMessageChannel(Objects.requireNonNull(getFlutterEngine()).getDartExecutor().getBinaryMessenger(),
                "com.flutter.BasicMessageChannel", StandardMessageCodec.INSTANCE);

        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), "com.RfidRead.rfidread")
                .setMethodCallHandler(
                        new MethodChannel.MethodCallHandler() {
                            @Override
                            public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
                                if (call.method.equals("InitRfid")) {
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            boolean InitResult = InitRfid();
                                            Log.v("设备型号", "" + ModelDevice);
                                            Log.v("注册广播完成", "注册广播完成");
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    result.success("" + InitResult);
                                                }
                                            });
                                        }
                                    }).start();
                                }
                                if (call.method.equals("ReadRfid")) {
                                    RFIDhandler = new Handler() {
                                        @Override
                                        public void handleMessage(Message msg) {
                                            super.handleMessage(msg);
                                            switch (msg.what) {
                                                case 1:
                                                    sendNativeMessage(msg.obj.toString());

                                                    break;
                                            }
                                        }
                                    };
//                                    Token = call.arguments().toString();
                                    // 读取标签
                                    ReadRFID();
                                    // result.success(RFIDvalue);
                                }
                                if (call.method.equals("ReadRFIDOne")) {
                                    ReadRFIDOnehandler = new Handler() {
                                        @Override
                                        public void handleMessage(Message msg) {
                                            super.handleMessage(msg);
                                            switch (msg.what) {
                                                case 1:
                                                    Log.v("rfid数据:", "" + msg.obj);

                                                    sendNativeMessage(msg.obj.toString());
                                                    break;
                                            }
                                        }
                                    };
                                    // 读取标签
                                    ReadRFIDOne();
                                    // result.success(RFIDvalue);
                                }
                                if (call.method.equals("StopReadRfid")) {
                                    // 停止读取标签
                                    StopRFID();
                                }
                                if (call.method.equals("onDestroy")) {
                                    // 销毁rfid模块
                                    DisConnectRFID();
                                }
                                if (call.method.equals("SetPower")) {
                                    int Power = Integer.parseInt(call.arguments.toString());
                                    RFIDSetPowerhandler = new Handler() {
                                        @Override
                                        public void handleMessage(Message msg) {
                                            super.handleMessage(msg);
                                            switch (msg.what) {
                                                case 1:
                                                    result.success(msg.obj);
                                                    break;
                                            }
                                        }
                                    };
                                    // 设置功率
                                    RfidSetPower(Power);

                                }
                                if (call.method.equals("GetPower")) {
                                    RFIDGetPowerhandler = new Handler() {
                                        @Override
                                        public void handleMessage(Message msg) {
                                            super.handleMessage(msg);
                                            switch (msg.what) {
                                                case 1:
                                                    result.success(msg.obj);
                                                    break;
                                            }
                                        }
                                    };
                                    // 查询功率
                                    RfidGetPower();
                                }
                                if (call.method.equals("InitScan")) {
                                    InitScanhandler = new Handler() {
                                        @Override
                                        public void handleMessage(Message msg) {
                                            super.handleMessage(msg);
                                            switch (msg.what) {
                                                case 1:
                                                    Log.v("Scan初始化:", "" + msg.obj);
                                                    result.success(msg.obj.toString());
                                                    break;
                                            }
                                        }
                                    };
                                    InitScan();
                                }
                                if (call.method.equals("DestoryScan")) {
                                    // 销毁Scan
                                    DestoryScan();
                                }
                                if (call.method.equals("StartScan")) {
                                    Scanhandler = new Handler() {
                                        @Override
                                        public void handleMessage(Message msg) {
                                            super.handleMessage(msg);
                                            switch (msg.what) {
                                                case 1:
                                                    Log.v("Scan数据:", "" + msg.obj);
                                                    result.success(msg.obj.toString());
                                                    break;
                                            }
                                        }
                                    };
                                    // 开始扫描
                                    StartScan();
                                }
                                if (call.method.equals("ClearTidList")) {

                                    // 清空
                                    ClearTidList();
                                }
                                if (call.method.equals("GetRfidMessageGet")) {

                                    // post网络请求标签信息
                                    String ID = call.argument("ID");
                                    String Url = call.argument("Url");
                                    String Token = call.argument("Token");
                                    GetRfidMessageGet(ID,Url,Token);
                                }
                                if (call.method.equals("GetRfidMessagePost")) {

                                    try {
                                        // post网络请求标签信息
                                        String ID = call.argument("ID");
                                        String Url = call.argument("Url");
                                        String Token = call.argument("Token");
                                        GetRfidMessagePost(ID,Url,Token);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }



                            }
                        });
        GeneratedPluginRegistrant.registerWith(flutterEngine);
        sendNativeMessage("初始化通道");
        // NativeBaseToFlutter.registerWith(this);
    }

    /**
     * java 发起通信
     *
     * @param
     */
    void sendNativeMessage(String msg) {
        messageChannel.send(msg, new BasicMessageChannel.Reply() {

            @Override
            public void reply(Object o) {
                Log.d("TAG", "flutter返回了数据:reply ");
            }
        });
    }


    //    初始化AUTOID UTouch(c)手持机
    public boolean InitRfid() {
        ///东集手持机
        UTouchUHF = UHFService.getInstance(MainActivity.this);

        if (UTouchUHF.open()) {
            init = true;
            byte[] embd = new byte[255];
            embd[0] = (byte) 2;
            embd[1] = (byte) 0;
            embd[2] = (byte) 12;
//            System.arraycopy(getHexByteArray(et_embeded_acpwd.getText().toString()), 0, embd, 3, 4);
            boolean IsSet = UTouchUHF.setParamBytes(UHFService.PARAMETER_TAG_EMBEDEDDATA, embd);
//            设置隐藏PC号
            boolean IsSetPC = UTouchUHF.setParameters(UHFService.PARAMETER_HIDE_PC, 1);
//            设置读取速度
            UTouchUHF.setParameters(UHFService.PARAMETER_INVENTORY_SPEED, 0);
            boolean IsSESSION = UTouchUHF.setParameters(UHFService.PARAMETER_INVENTORY_SESSION, 0);
            boolean IsProfile = UTouchUHF.setParameters(UHFService.PARAMETER_LINK_PROFILE, 1);
            Log.v("是否设置成功", "" + IsSESSION + ",隐藏PC" + IsSetPC + ",设置附加数据" + IsSet + ",灵敏度" + IsProfile);
//            UTouchUHF.registerReadTags(mIReadTagsListener);

        } else {
            init = false;
        }
        return init;
    }

    // 设置AUTOID UTouch(c)手持机功率
    public void RfidSetPower(int Power) {
        ///东集手持机
        if (UTouchUHF != null) {
            boolean IsSet = false;
            // 设置功率
            IsSet = UTouchUHF.setPower(Power);
            Log.v("设置功率:", "" + IsSet);
            Message message = new Message();
            message.what = 1;
            message.obj = IsSet;
            RFIDSetPowerhandler.sendMessage(message);
        }
    }
    // 查询AUTOID UTouch(c)手持机功率
    public void RfidGetPower() {
        //、东集手持机
        if (UTouchUHF != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int Power = 0;
                    Power = UTouchUHF.getPower();
                    Log.v("模块功率:", "" + Power);
                    Message message = new Message();
                    message.what = 1;
                    message.obj = Power;
                    RFIDGetPowerhandler.sendMessage(message);
                }
            }).start();
        }
    }

    // 销毁AUTOID UTouch(c)手持机模块
    public void DisConnectRFID() {
        ///东集手持机
        if (UTouchUHF != null) {// close uhf module
            // 停止识别
            StopRFID();
            init = false;
            UTouchUHF.close();
//            UTouchUHF.unregisterReadTags(mIReadTagsListener);
            UTouchUHF = null;
        }
    }

    //    开始单次读取
    public void ReadRFIDOne() {

        ///东集手持机
        if (UTouchUHF != null) {
////       单次读取
            EPC epc = new EPC();
            if (UTouchUHF.inventoryOnce(epc, 100)) {
                String EPC = epc.getId();
                Log.v("epc:", "" + EPC);
                Log.v("信号强度", "" + epc.rssi);
                if (EPC != null && !"".equals(EPC)) {
                    try {
                        SoundTool.getInstance(MainActivity.this).playBeep(1);
                        JSONObject data = new JSONObject();
                        data.put("Type", "RFID");
                        data.put("Rfid", EPC);
                        data.put("Epc", EPC);
                        data.put("IsSearch", "false");
                        data.put("Rssi", "" + epc.rssi);
                        Message message = new Message();
                        message.what = 1;
                        message.obj = data;
                        ReadRFIDOnehandler.sendMessage(message);
                    } catch (Exception e) {

                    }
                }
            }


        }
    }
    // 开始循环读取AUTOID UTouch(c)手持机
    public void ReadRFID() {

        ///东集手持机
        if (UTouchUHF != null) {
            List<String> EPClist = new ArrayList<String>();
            if (UTouchUHF.inventoryStart()) {
                Log.v("inventoryStart","盘存开启成功");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mInventoryStart = true;
                        JSONObject data = new JSONObject();
                        while (mInventoryStart) {
                            try {
                                Thread.sleep(100);
                                List<EPC> epcList = UTouchUHF.getTagIDs();
                                UTouchUHF.setParameters(UHFService.PARAMETER_CLEAR_EPCLIST, 1);
                                if (epcList.size() > 0) {
                                    SoundTool.getInstance(MainActivity.this).playBeep(1);
                                    try {
                                        String TID = "";
                                        Log.v("EPC列表长度", "" + epcList.size() + "列表内容:" + epcList);
                                        for (int i = 0; i < epcList.size(); i++) {

                                            if (epcList.get(i).getId() != null && epcList.get(i).getId().length() > 4) {
                                                TID = epcList.get(i).getEmbeded();
                                                if (TID.contains("000000000000000000000000") || TID.isEmpty()) {
                                                    Log.e("TID不可用", "" + TID + "强度:" + epcList.get(i).rssi);
                                                } else {
                                                    data.put("Type", "RFID");
                                                    data.put("Rfid", ""+epcList.get(i).getId());
                                                    data.put("Epc",""+epcList.get(i).getId());
                                                    data.put("Rssi", "" + epcList.get(i).rssi);
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            sendNativeMessage(data.toString());
                                                        }
                                                    });
                                                }
                                            }

                                        }

                                    } catch (Exception e) {

                                    }
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();
            }else {
                Log.v("inventoryStart","盘存开启失败");
            }

        }
    }

    public void ClearTidList() {
        TIDlist.clear();
        mEPCList.clear();
    }

    // 停止读取AUTOID UTouch(c)手持机
    public void StopRFID() {
        mInventoryStart = false;
        System.out.println("begin stop!!");

        ///东集手持机
        if (UTouchUHF.inventoryStop()) {
            System.out.println("end stop!!");
        } else {
            System.out.println("RfidInventoryStop faild.");
        }

        return;
    }

    // *******************扫描***************
    // 打开扫描
    public void InitScan() {

        ///东集手持机
        Log.v("开始初始化扫描器", "开始初始化扫描器");
        mScanKeyService = ScanKeyService.getInstance();
        mCallback = new IKeyEventCallback.Stub() {
            @Override
            public void onKeyDown(int keyCode) throws RemoteException {
            }

            @Override
            public void onKeyUp(int keyCode) throws RemoteException {
            }
        };
//            InitScanCallBack();
        Log.v("扫描器监听摁键对象", "" + mCallback);
        mScanKeyService.registerCallback(mCallback, "249,250");
        scanner = ScannerFactory.getScanner(this);
        scanner.open();
        scanner.setDecodeInfoCallBack(this);



    }

    // 开始扫描
    public void StartScan() {
        scanner.startScan();
    }

    // 销毁扫描
    public void DestoryScan() {
        if (scanner != null) {
            scanner.close();
            scanner.setDecodeInfoCallBack(null);
            scanner = null;
        }
        mScanKeyService.unregisterCallback(mCallback);
//        销毁扫描广播i
//        unregisterReceiver(myBroadcastReceiver);
        Log.v("卸载广播完成", "卸载广播完成");
    }


    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        super.onPointerCaptureChanged(hasCapture);
    }

    class MyBroadcastReceiver extends BroadcastReceiver {//广播接收器

        @Override
        public void onReceive(Context context, Intent intent) {
            //Toast.makeText(context, "network changes", Toast.LENGTH_SHORT).show();
            String msg = intent.getStringExtra("scannerdata");
            JSONObject Objectdata = new JSONObject();
            try {
                Objectdata.put("Type", "Scan");
                Objectdata.put("ScanData", msg);
                Objectdata.put("Rssi", "");
                //            传给Flutter
                sendNativeMessage(Objectdata.toString());
                Log.d("receiver", "onReceive: " + msg);
                return;
            } catch (Exception e) {

            }
        }

    }

    /////**************************东集手持机监听摁键********************************//
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Num++;
        Log.v("keycode", "" + event.getScanCode());
        Log.v("摁下次数", "" + Num);
        if (event.getScanCode() == 249 && Num == 1) {
            scanner.startScan();
        }
        if (event.getScanCode() == 250 && init && Num == 2) {
            JSONObject data = new JSONObject();
            try {
                data.put("Rfid", "");
                data.put("Type", "onKeyDown");
                data.put("Rssi", "");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    sendNativeMessage(data.toString());
                }
            });
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        Num = 0;
        Log.v("扫描摁键抬起", "" + event.getScanCode());
        Log.v("抬起次数", "" + Num);
        if (event.getScanCode() == 249) {
            scanner.stopScan();
        }
        if (event.getScanCode() == 250 && init) {
            JSONObject data = new JSONObject();
            try {
                data.put("Rfid", "");
                data.put("Type", "onKeyUp");
                data.put("Rssi", "");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    sendNativeMessage(data.toString());
                }
            });
        }
        return super.onKeyUp(keyCode, event);
    }

    /*按键按下抬起执行扫描和 停止扫码的功能*/
    public void InitScanCallBack() {
        mCallback = new IKeyEventCallback.Stub() {
            @Override
            public void onKeyDown(int keyCode) throws RemoteException {

            }

            @Override
            public void onKeyUp(int keyCode) throws RemoteException {

            }
        };
    }

    public void onDecodeComplete(final DecodeInfo decodeInfo) {
        SoundTool.getInstance(MainActivity.this).playBeep(1);
        Message msg = new Message();
        msg.what = 1;
        msg.obj = decodeInfo.barcode;
        handler.sendMessage(msg);
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    JSONObject Objectdata = new JSONObject();
                    try {
                        Objectdata.put("Type", "Scan");
                        Objectdata.put("ScanData", msg.obj.toString());
                        Objectdata.put("Rssi", "");
                        //            传给Flutter
                        sendNativeMessage(Objectdata.toString());
                        Log.v("扫描信息", "" + msg.obj.toString());
                        return;
                    } catch (Exception e) {

                    }
                    break;
                default:
                    break;
            }
        }

        ;
    };


    //网络请求****************************//
    //    获取信息(GET方法)
    public void GetRfidMessageGet(String ID,String Url,String Token) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                    Date date = new Date(System.currentTimeMillis());
                    Log.i("开始请求时间", "" + simpleDateFormat.format(date) + "线程id:" + Thread.currentThread().getId());
                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(Url+"?RFIDCode=" + ID)
                            .get()
                            .addHeader("Cookie", Token)
                            .build();
                    Response response = okHttpClient.newCall(request).execute();
                    String responseData = response.body().string();
                    handleResponse(responseData,ID);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }
    //    获取信息(POST方法)
    public  void GetRfidMessagePost(String ID,String Url,String Token) throws JSONException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Log.d("请求参数",""+ID);
                    Log.d("请求地址",""+Url);
                    Log.d("请求token",""+Token);
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                    Date date = new Date(System.currentTimeMillis());
                    Log.i("开始请求时间", "" + simpleDateFormat.format(date) + "线程id:" + Thread.currentThread().getId());


                    OkHttpClient client = new OkHttpClient();
                    MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
                    //post方式提交的数据
                    FormBody body = new FormBody.Builder()
                            .add("RFIDCode", ID)
                            .build();

                    JSONObject json=new JSONObject();
//                    json.put("RFIDCode",ID);
//                    RequestBody body = RequestBody.create(mediaType, json.toString());
                    Log.d("请求参数",""+body);
                    Request request = new Request.Builder()
                            .url(Url)
                            .post(body)
                            .addHeader("Cookie", "Token="+Token)
                            .addHeader("content-type", "application/x-www-form-urlencoded")
                            .build();
                    //2.创建一个call对象,参数就是Request请求对象
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    Log.i("MainActivity","数据返回"+responseData);
                    handleResponse(responseData,ID);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    //处理网络请求的结果
    private void handleResponse(String responseData,String ID) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            Date date = new Date(System.currentTimeMillis());
            Log.i("结束请求时间", "" + simpleDateFormat.format(date) + "线程id:" + Thread.currentThread().getId());

            JSONObject jsonObject = new JSONObject(responseData);
            Log.v("返回数据", "" + responseData);
            Map<String, String> MapData = new HashMap<String, String>();
            if (jsonObject.getInt("code") == 0) {
                JSONObject param = jsonObject.getJSONObject("data");
                JSONObject data = new JSONObject();
                data.put("Type", "Request");
                data.put("Data", param);
//                data.put("TIDlistCount", TIDlist.size());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        sendNativeMessage(data.toString());
                    }
                });
            } else {
                JSONObject data = new JSONObject();
                data.put("Type", "Request");
                data.put("Data", "");
                data.put("EPC", ID);
//                data.put("TIDlistCount", TIDlist.size());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        sendNativeMessage(data.toString());
                    }
                });
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}
